package com.ff.neuropp.controller;


import com.ff.neuropp.domain.Auth;
import com.ff.neuropp.domain.Role;
import com.ff.neuropp.domain.SystemLog;
import com.ff.neuropp.domain.User;
import com.ff.neuropp.jwt.JwtHelper;
import com.ff.neuropp.service.AuthService;
import com.ff.neuropp.service.RoleService;
import com.ff.neuropp.service.SystemLogService;
import com.ff.neuropp.service.UserService;
import com.ff.neuropp.util.ResultTool;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.*;

/**
 * 账号管理
 */
@RestController
@RequestMapping("/api/user")
@Api(value = "账号管理controller", tags = {"账号管理接口"})
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private SystemLogService systemLogService;

    @Resource
    private AuthService authService;

    @Resource
    private RoleService roleService;


    @ApiOperation(value = "根据id获取用户", notes = "根据id获取用户")
    @GetMapping(value = "/findbyid")
    public Map<String, Object> getUserById(@ApiParam(value = "用户id", required = true) @RequestBody Integer id) {
        Map<String, Object> result = new HashMap<>();
        User user = userService.findById(id);
        if (null == user) {
            result.put("code", 10001);
            result.put("message", "未查询到此用户");
            return result;
        }
        result.put("data", user);
        result.put("code", 10000);
        result.put("message", "获取成功");
        return result;
    }


    @PostMapping("/login")
    @ApiOperation(value = "用户登录接口", notes = "用户登录")
    public Map<String, Object> loginUser(@ApiParam(required = true, value = "登录帐号") @RequestParam String account,
                                         @ApiParam(required = true, value = "登录密码") @RequestParam String password,
                                         HttpServletRequest request) throws Exception {

        Map<String, Object> result = new HashMap<>();
        User user = userService.findUserByAccount(account);
        if (null != user) {
            if (user.getPassword().equals(password)) {
                if (null != user.getStatus() && user.getStatus() == 0) {
                    result.put("code", 10003);
                    result.put("message", "帐号异常，请联系管理员");
                    return result;
                }
                result.put("code", 10000);
                result.put("message", "登录成功");

                SystemLog systemLog = new SystemLog();
                systemLog.setLogAccount(account);
                systemLog.setLogName(user.getName());
                systemLog.setLogJobNumber(user.getJobNumber());
                String url = request.getServletPath();
                systemLog.setLogurl(url);
                Auth auth = authService.findByUrl(url);
                if (null != auth) {
                    systemLog.setLogContent(auth.getName());
                }
                systemLog.setLogIp(request.getRemoteHost());
                systemLogService.save(systemLog);

                Map<String, Object> data = new HashMap<String, Object>();
                data.put("token", JwtHelper.generateToken(account));
                result.put("data", data);
            } else {
                result.put("code", 10001);
                result.put("message", "密码错误");
            }
        } else {
            result.put("code", 10002);
            result.put("message", "用户不存在");
        }
        return result;
    }

    @PostMapping("/logout")
    @ApiOperation(value = "用户退出接口", notes = "用户退出")
    public Map<String, Object> loginUser(HttpServletRequest request) throws Exception {
        Map<String, Object> result = new HashMap<>();
        //HttpSession httpSession = request.getSession();
        //httpSession.removeAttribute("loginUser");
        result.put("code", 10000);
        return result;
    }

    @PostMapping("/changepw")
    @ApiOperation(value = "用户修改密码接口", notes = "修改密码")
    public Map<String, Object> changePassword(@ApiParam(required = true, value = "旧密码") @RequestParam String oldpassword,
                                              @ApiParam(required = true, value = "新密码") @RequestParam String newpassword,
                                              HttpServletRequest request) throws Exception {
        Map<String, Object> result = new HashMap<>();
        String token = request.getHeader("token");
        String account = JwtHelper.parseToken(token);
        User user = userService.findUserByAccount(account);
        if (null != user && null != oldpassword) {
            if (user.getPassword().equals(oldpassword)) {
                user.setPassword(newpassword);
                userService.saveUser(user);
                result.put("message", "密码修改完成");
                result.put("code", 10000);
            } else {
                result.put("code", 10001);
                result.put("message", "旧密码验证失败");
            }

        } else {
            result.put("code", 10001);
            result.put("message", "修改密码失败");
        }

        return result;
    }

    @GetMapping("/info")
    @ApiOperation(value = "用户信息获取", notes = "获取登录用户信息")
    public Map<String, Object> getInfo(@ApiParam(required = false, value = "登录帐号") @RequestParam(required = false) String account,
                                       HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        String token = request.getHeader("token");
        if (null != token) {
            account = JwtHelper.parseToken(token);
            User user = userService.findUserByAccount(account);
            if (null == user) {
                result.put("code", 10003);
                result.put("message", "用户不存在");
                return result;
            }
            Map<String, Object> data = new HashMap<String, Object>();
            List<String> roles = new ArrayList<String>();
            Role role = user.getRole();
            if (null != role) {
                List<Auth> auths = role.getAuths();
                if (null != auths && auths.size() > 0) {
                    for (Auth auth : auths) {
                        roles.add(auth.getName());
                    }
                }
            }
            //roles.add("admin");
            data.put("roles", roles);
            data.put("name", user.getName());
            result.put("code", 10000);
            result.put("data", data);
        } else {
            result.put("code", 10002);
            result.put("message", "用户不存在");
        }

        return result;

    }

    @PostMapping("/getinfo")
    @ApiOperation(value = "查询个人信息", notes = "查询个人信息")
    public Map<String, Object> getUserInfo(HttpServletRequest request) throws Exception {
        Map<String, Object> result = new HashMap<>();
        String token = request.getHeader("token");
        String account = JwtHelper.parseToken(token);
        User user = userService.findUserByAccount(account);
        if (null == user) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "登录超时");
        }
        result.put("data", user);
        result.put("code", 10000);
        result.put("message", "获取个人信息成功");
        return result;
    }

    @PostMapping("/updateinfo")
    @ApiOperation(value = "个人信息维护", notes = "个人信息维护")
    public Map<String, Object> updateUserInfo(@ApiParam(required = false, value = "姓名") @RequestParam(required = false) String name,
                                              @ApiParam(required = false, value = "手机") @RequestParam(required = false) String phone,
                                              @ApiParam(required = false, value = "邮箱") @RequestParam(required = false) String email,
                                              @ApiParam(required = false, value = "工号") @RequestParam(required = false) String jobNumber,
                                              @ApiParam(required = false, value = "科室") @RequestParam(required = false) String dept,
                                              @ApiParam(required = false, value = "性别") @RequestParam(required = false) Integer sex,
                                              @ApiParam(required = false, value = "工号") @RequestParam(required = false) String oldPassword,
                                              @ApiParam(required = false, value = "工号") @RequestParam(required = false) String password,
                                              @ApiParam(required = false, value = "昵称") @RequestParam(required = false) String nickName,
                                              HttpServletRequest request) throws Exception {
        Map<String, Object> result = new HashMap<>();
        String token = request.getHeader("token");
        String account = JwtHelper.parseToken(token);
        User user = userService.findUserByAccount(account);
        if (null == user) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "登录超时");
        }
        user.setName(name);
        user.setPhone(phone);
        user.setEmail(email);
        user.setJobNumber(jobNumber);
        user.setDept(dept);
        user.setSex(sex);
        user.setNickName(nickName);
        user.setPassword(password);
        userService.saveUser(user);

        return ResultTool.genSuccessResult("更新个人信息成功");
    }


    @PostMapping("/setrole")
    @ApiOperation(value = "设置用户角色", notes = "设置用户角色")
    public Map<String, Object> setUserRole(@ApiParam(required = true, value = "用户id") @RequestParam(required = true) Integer userId,
                                           @ApiParam(required = true, value = "角色id") @RequestParam(required = true) Integer roleId) {
        Map<String, Object> result = new HashMap<>();
        User user = userService.findById(userId);
        if (null == user) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "用户不存在");
        }
        Role role = roleService.findById(roleId);
        if (null == role) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "角色不存在");
        }
        user.setRole(role);
        userService.saveUser(user);
        result.put("code", 10000);
        result.put("message", "设置成功");
        return result;
    }

    @GetMapping("/getauths")
    @ApiOperation(value = "获取角色权限", notes = "设置角色权限")
    public Map<String, Object> setRoleAuth(@ApiParam(required = true, value = "角色id") @RequestParam(required = true) Integer roleId) throws Exception {
        Map<String, Object> result = new HashMap<>();
        Role role = roleService.findById(roleId);
        if (null == role) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "角色不存在");
        }
        ;
        List<Integer> authList = new ArrayList<>();
        List<Auth> auths = role.getAuths();
        if (null != auths && auths.size() > 0) {
            for (Auth auth : auths) {
                authList.add(auth.getId());
            }
        }
        result.put("authList", authList);
        result.put("code", 10000);
        return result;
    }

    @PostMapping("/setauths")
    @ApiOperation(value = "设置角色权限", notes = "设置角色权限")
    public Map<String, Object> setRoleAuth(@ApiParam(required = true, value = "角色id") @RequestParam(required = true) Integer roleId,
                                           @ApiParam(required = true, value = "权限列表") @RequestParam(required = true) String auths) throws Exception {
        Role role = roleService.findById(roleId);
        if (null == role) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "角色不存在");
        }
        List<Auth> authList = new ArrayList<>();
        if (null != auths && auths.length() > 0) {
            String[] authStrList = auths.split(",");
            for (String idStr : authStrList) {
                Auth auth = authService.findById(Integer.valueOf(idStr));
                if (null != auth) {
                    authList.add(auth);
                }
            }
        }
        role.setAuths(authList);
        roleService.saveRole(role);
        return ResultTool.genSuccessResult("设置完成");
    }

    @GetMapping("/list")
    @ApiOperation(value = "查询用户列表", notes = "查询用户列表")
    public Map<String, Object> findList(@ApiParam(required = false, value = "姓名") @RequestParam(required = false) String name,
                                        @ApiParam(required = false, value = "账号") @RequestParam(required = false) String account,
                                        @ApiParam(required = false, value = "电话") @RequestParam(required = false) String phone,
                                        @ApiParam(required = false, value = "关键词") @RequestParam(required = false) String tag,
                                        HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        /*Map<String, Object> param = new HashMap<>();
        param.put("GT_id", 0);
        if (null != name && name.length() > 0) {
            param.put("LIKE_name", name);
        }
        if (null != account && account.length() > 0) {
            param.put("LIKE_account", account);
        }
        if (null != phone && phone.length() > 0) {
            param.put("LIKE_phone", phone);
        }*/
        List<User> list = userService.findListByTag(tag);
        if (null != list && list.size() > 0) {
            result.put("data", list);
            result.put("total", list.size());
            result.put("message", "查询成功");
            result.put("code", 10000);
        } else {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1,"没有查询到数据");
        }

        return result;
    }

    @PostMapping("/update")
    @ApiOperation(value = "更新用户信息", notes = "更新用户信息")
    public Map<String, Object> updateUser(@Valid User user, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        User bak = userService.findById(user.getId());
        if(null == bak) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1,"编辑错误");
        }
        user.setPassword(bak.getPassword());
        userService.saveUser(user);

        result.put("code", 10000);
        result.put("message", "修改成功");
        return result;
    }

    @PostMapping("/create")
    @ApiOperation(value = "新增用户信息", notes = "新增用户信息")
    public Map<String, Object> saveUser(@Valid User user, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        userService.saveUser(user);

        result.put("code", 10000);
        result.put("message", "添加成功");
        return result;
    }

    @PostMapping("/delete")
    @ApiOperation(value = "删除用户信息", notes = "删除用户信息")
    public Map<String, Object> deleteUser(@ApiParam(required = true, value = "用户id") @RequestParam String id) {
        Map<String, Object> result = new HashMap<>();

        userService.deleteUser(Integer.valueOf(id));

        result.put("code", 10000);
        result.put("message", "删除成功");
        return result;
    }

    @PostMapping("/activteuser")
    @ApiOperation(value = "激活封号", notes = "激活封号")
    public Map<String, Object> activateUser(@ApiParam(required = true, value = "帐号") @RequestParam String account,
                                            @ApiParam(required = true, value = "状态 1=激活 0=封号") @RequestParam Integer status) {
        Map<String, Object> result = new HashMap<>();
        User user = userService.findUserByAccount(account);
        if(null == user) {
            result.put("code", 10001);
            result.put("message", "用户未找到");
            return result;
        }
        user.setStatus(status);
        userService.saveUser(user);
        result.put("code", 10000);
        result.put("message", "设置成功");
        return result;
    }


}
